package org.com.java_chatroom.api;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.com.java_chatroom.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@ResponseBody
public class MessageSessionAPI {
    @Autowired
    private MessageSessionMapper messageSessionMapper;
    @Autowired
    private MessageMapper messageMapper;

    //    查询当前用户包含哪些回话
    @RequestMapping("/sessionList")
    public Object getSessionByUserId(HttpServletRequest req){
        HttpSession session = req.getSession(false);
        if(session==null){
            System.out.println("[MessageSessionAPI] getSessionByUserId :session==null");
            return new ArrayList<MessageSession>();
        }
        User user = (User) session.getAttribute("user");
        if(user==null){
            System.out.println("[MessageSessionAPI] getSessionByUserId: user==null");
            return new ArrayList<MessageSession>();
        }
        int userId = user.getUserId();
        List<Integer> sessionIds = messageSessionMapper.getSessionIdsByUserId(userId);
//       创建messageSession结果集:
        List<MessageSession> messageSessions = new ArrayList<>();
//        遍历sessionId,构造MessageSession对象:
        for(int sessionId:sessionIds){
//            System.out.println("sessionId:"+sessionId);
//            构造会话对象:
            MessageSession messageSession = new MessageSession();
//            设置sessionId:
            messageSession.setSessionId(sessionId);
//           设置好友列表:
            List<Friend> friends = messageSessionMapper.getFriendsBySessionId(sessionId, userId);

            messageSession.setFriends(friends);
//            设置最近一次会话内容:
            String lastMessage = messageMapper.getLastMessageBySessionId(sessionId);
            if(lastMessage==null){
                lastMessage = "";
            }
            messageSession.setLastMessage(lastMessage);
//            将会话添加到结果集中:
            messageSessions.add(messageSession);
        }
        return messageSessions;
    }

//    新增会话,将数据存储到数据库中:
    @RequestMapping("/session")
//    通过@SessionAttribute注解获取user,这种方法弊端就是当获取失败时,就会直接抛出异常,无法自定义处理
    @Transactional //由于这个方法中存在多个数据库插入操作,可能出现数据库插入失败的情况,这样数据就乱了,
                    // 因此需要通过事务机制,来实现失败时的回滚机制
    public Object addSession(int toUserId, @SessionAttribute("user") User user){
        Map<String,Integer> hash = new HashMap<>();
//        进行数据库的插入操作
//        1.向message_session表中插入数据
        MessageSession messageSession = new MessageSession();
        messageSessionMapper.addMessageSession(messageSession);
//        2.向message_session_user中插入两条数据
//        第一条:
        MessageSessionUser messageSessionUser1 = new MessageSessionUser();
        messageSessionUser1.setSessionId(messageSession.getSessionId());
        messageSessionUser1.setUserId(user.getUserId());
        messageSessionMapper.addMessageSessionUser(messageSessionUser1);
//        第二条:
        MessageSessionUser messageSessionUser2 = new MessageSessionUser();
        messageSessionUser2.setSessionId(messageSession.getSessionId());
        messageSessionUser2.setUserId(toUserId);
        messageSessionMapper.addMessageSessionUser(messageSessionUser2);
        System.out.println("[MessageSession] addSession 新增一条会话成功!");
        hash.put("sessionId",messageSession.getSessionId());
        return hash;
    }

}
